
<!DOCTYPE html>
<html lang="en" class="loading">
<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Go Xorm框架笔记 - kyralo</title>
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate">
    <meta name="keywords" content="kyralo,"> 
    <meta name="description" content="一、创建engineengine, err := xorm.NewEngine(driverName, dataSourceName)
上述代码创建了一个数据库引擎，可以在一个程序中创建多个engi,"> 
    <meta name="author" content="kyralo"> 
    
    <link rel="icon" href="https://cdn.jsdelivr.net/gh/kyralo/cdn/ico/favicon.ico"> 
    <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kyralo/cdn@v1.0.2/css/diaspora.css">
    <!-- <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> -->
    <script>
         (adsbygoogle = window.adsbygoogle || []).push({
              google_ad_client: "ca-pub-8691406134231910",
              enable_page_level_ads: true
         });
    </script>
    <!-- <script async custom-element="amp-auto-ads"
        src="https://cdn.ampproject.org/v0/amp-auto-ads-0.1.js">
    </script> -->
</head>
</html>
<body class="loading">
    <span id="config-title" style="display:none">kyralo</span>
    <div id="loader"></div>
    <div id="single">
    <div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <a class="icon-home image-icon" href="javascript:;" data-url="https://kyralo.github.io"></a>
    <!-- <div title="播放/暂停" class="icon-play"></div> -->
    <h3 class="subtitle">Go Xorm框架笔记</h3>
    <div class="social">
        <div>
            <div class="share">
                <a title="获取二维码" class="icon-scan" href="javascript:;"></a>
            </div>
            <div id="qr"></div>
        </div>
    </div>
    <div class="scrollbar"></div>
</div>

    <div class="section">
        <div class="article">
    <div class='main'>
        <h1 class="title">Go Xorm框架笔记</h1>
        <div class="stuff">
            <span>九月 17, 2019</span>
            
  <ul class="post-tags-list"><li class="post-tags-list-item"><a class="post-tags-list-link" href="/tags/Go/">Go</a></li><li class="post-tags-list-item"><a class="post-tags-list-link" href="/tags/Xorm/">Xorm</a></li></ul>


        </div>
        <div class="content markdown">
            <h3 id="一、创建engine"><a href="#一、创建engine" class="headerlink" title="一、创建engine"></a>一、创建engine</h3><pre><code>engine, err := xorm.NewEngine(driverName, dataSourceName)
上述代码创建了一个数据库引擎，可以在一个程序中创建多个engine。</code></pre><h3 id="二、查询方法："><a href="#二、查询方法：" class="headerlink" title="二、查询方法："></a>二、查询方法：</h3><h4 id="2-1、支持sql查询："><a href="#2-1、支持sql查询：" class="headerlink" title="2.1、支持sql查询："></a>2.1、支持sql查询：</h4><pre><code>1、查询一个string类型的sql，返回[]map[string][]byte类型的切片（查询）
results, err := engine.Query(&quot;select * from user&quot;)

2、执行一个string的sql，返回结果影响行数（增删改）
affected, err := engine.Exec(&quot;update user set .... where ...&quot;)</code></pre><h4 id="2-2、ORM方法："><a href="#2-2、ORM方法：" class="headerlink" title="2.2、ORM方法："></a>2.2、ORM方法：</h4><h3 id="主要有七个方法和其他辅助的方法来操作数据库。"><a href="#主要有七个方法和其他辅助的方法来操作数据库。" class="headerlink" title="主要有七个方法和其他辅助的方法来操作数据库。"></a>主要有七个方法和其他辅助的方法来操作数据库。</h3><p>　　1、插入一个或者多个数据：</p>
<pre><code>affected, err := engine.Insert(&amp;struct)
// INSERT INTO struct () values ()
affected, err := engine.Insert(&amp;struct1, &amp;struct2)
// INSERT INTO struct1 () values ()
// INSERT INTO struct2 () values ()
affected, err := engine.Insert(&amp;sliceOfStruct)
// INSERT INTO struct () values (),(),()
affected, err := engine.Insert(&amp;struct1, &amp;sliceOfStruct2)
// INSERT INTO struct1 () values ()
// INSERT INTO struct2 () values (),(),()


has, err := engine.Get(&amp;user)
// SELECT * FROM user LIMIT 1</code></pre><p>　　3、从数据库中查询多条记录：</p>
<pre><code>sliceOfStructs := new(Struct)
err := engine.Find(sliceOfStructs)
// SELECT * FROM user</code></pre><p>　　4、查询多条记录，然后每条记录进行处理，有两个方法，一个是iterator，另一个是raw：</p>
<pre><code>err := engine.Iterate(...)
// SELECT * FROM user

raws, err := engine.Raws(...)
// SELECT * FROM user
bean := new(Struct)
for raws.Next() {
    err = raws.Scan(bean)
}</code></pre><p>　　5、更新一条或者多条记录：</p>
<pre><code>affected, err := engine.Update(&amp;user)
// UPDATE user SET ...
　　6：删除一条或者多条记录，必须存在删除条件

affected, err := engine.Where(...).Delete(&amp;user)
// DELETE FROM user Where ...</code></pre><p>　　7、查询记录条数:</p>
<pre><code>counts, err := engine.Count(&amp;user)
// SELECT count(*) AS total FROM user</code></pre><h4 id="2-3：条件："><a href="#2-3：条件：" class="headerlink" title="2.3：条件："></a>2.3：条件：</h4><p>　　1、Id、In：</p>
<pre><code>engine.Id(1).Get(&amp;user) // for single primary key
// SELECT * FROM user WHERE id = 1
engine.Id(core.PK{1, 2}).Get(&amp;user) // for composite primary keys
// SELECT * FROM user WHERE id1 = 1 AND id2 = 2
engine.In(&quot;id&quot;, 1, 2, 3).Find(&amp;users)
// SELECT * FROM user WHERE id IN (1, 2, 3)
engine.In(&quot;id&quot;, []int{1, 2, 3})
// SELECT * FROM user WHERE id IN (1, 2, 3)</code></pre><p>　　2、 Where, And, Or</p>
<pre><code>engine.Where().And().Or().Find()
// SELECT * FROM user WHERE (.. AND ..) OR ...</code></pre><p>　　3、OrderBy, Asc, Desc</p>
<pre><code>engine.Asc().Desc().Find()
// SELECT * FROM user ORDER BY .. ASC, .. DESC
engine.OrderBy().Find()
// SELECT * FROM user ORDER BY ..</code></pre><p>　　4、 Limit, Top</p>
<pre><code>engine.Limit().Find()
// SELECT * FROM user LIMIT .. OFFSET ..
engine.Top(5).Find()
// SELECT TOP 5 * FROM user // for mssql
// SELECT * FROM user LIMIT .. OFFSET 0 //for other databases</code></pre><p>　　5、Sql, 查询原生SQL</p>
<pre><code>engine.Sql(&quot;select * from user&quot;).Find()</code></pre><p>　　6、Cols, Omit, Distinct</p>
<pre><code>engine.Cols(&quot;col1, col2&quot;).Find()
// SELECT col1, col2 FROM user
engine.Cols(&quot;col1&quot;, &quot;col2&quot;).Where().Update(user)
// UPDATE user set col1 = ?, col2 = ? Where ...
engine.Omit(&quot;col1&quot;).Find()
// SELECT col2, col3 FROM user
engine.Omit(&quot;col1&quot;).Insert()
// INSERT INTO table (non-col1) VALUES ()
engine.Distinct(&quot;col1&quot;).Find()
// SELECT DISTINCT col1 FROM user</code></pre><p>　　7、Join, GroupBy, Having</p>
<pre><code>engine.GroupBy(&quot;name&quot;).Having(&quot;name=&apos;xlw&apos;&quot;).Find()
//SELECT * FROM user GROUP BY name HAVING name=&apos;xlw&apos;
engine.Join(&quot;LEFT&quot;, &quot;userdetail&quot;, &quot;user.id=userdetail.id&quot;).Find()
//SELECT * FROM user LEFT JOIN userdetail ON user.id=userdetail.id</code></pre>
        </div>
        
    <div id='gitalk-container' class="comment link"
        data-ae='false'
        data-ci='eeec43124e53633945c0'
        data-cs='e2332cffb30ae24f185c1701286958cddd748ffb'
        data-r='kyralo.github.io'
        data-o='kyralo'
        data-a='kyralo'
        data-d='false'
    >查看评论</div>


    </div>
    
        <div class='side'>
            <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#一、创建engine"><span class="toc-number">1.</span> <span class="toc-text">一、创建engine</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#二、查询方法："><span class="toc-number">2.</span> <span class="toc-text">二、查询方法：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2-1、支持sql查询："><span class="toc-number">2.1.</span> <span class="toc-text">2.1、支持sql查询：</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-2、ORM方法："><span class="toc-number">2.2.</span> <span class="toc-text">2.2、ORM方法：</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#主要有七个方法和其他辅助的方法来操作数据库。"><span class="toc-number">3.</span> <span class="toc-text">主要有七个方法和其他辅助的方法来操作数据库。</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#2-3：条件："><span class="toc-number">3.1.</span> <span class="toc-text">2.3：条件：</span></a></li></ol></li></ol>
        </div>
    
</div>


    </div>
</div>
</body>
<script src="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script src="//lib.baomitu.com/jquery/1.8.3/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/gh/kyralo/cdn/js/plugin.js"></script>
<script src="//cdn.jsdelivr.net/gh/kyralo/cdn/js/diaspora.js"></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/kyralo/cdn/css/photoswipe.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/kyralo/cdn/css/default-skin.css">
<script src="//cdn.jsdelivr.net/gh/kyralo/cdn/js/photoswipe.min.js"></script>
<script src="//cdn.jsdelivr.net/gh/kyralo/cdn/js/photoswipe-ui-default.min.js"></script>

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



<!-- Google Analytics -->
<script type="text/javascript">
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-146789315-1', 'auto');
  ga('send', 'pageview');
</script>
<!-- End Google Analytics -->


<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer@1.10/dist/APlayer.min.css">
<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10/dist/APlayer.min.js"></script>
<style>
  .aplayer .aplayer-lrc {
    height: 35px;
  }
  .aplayer .aplayer-lrc p{
    font-size: 16px;
    font-weight: 700;
    line-height: 18px !important;
  }
  .aplayer .aplayer-lrc p.aplayer-lrc-current{
    color: #FF1493;
  }
  .aplayer.aplayer-narrow .aplayer-body{
    left: -66px !important;
  }
  .aplayer.aplayer-fixed .aplayer-lrc {
    display: none;
  }
  .aplayer .aplayer-lrc.aplayer-lrc-hide {
      display:none !important;
  }
  .aplayer.aplayer-fixed .lrc-show {
    display: block;
    background: rgba(255, 255, 255, 0.8);
  }
</style>
<div class="aplayer"

    data-id="2725346449"

    data-server="netease"

    data-type="playlist"

    data-fixed="true"

    data-autoplay="false"

    data-loop="all"

    data-order="random"

    data-preload="auto"

    data-volume="0.7"

    data-mutex="true"

</div>
<script src="https://cdn.jsdelivr.net/npm/meting@1.2/dist/Meting.min.js"></script>
<script>
  $(function(){
    $('body').on('click', '.aplayer', function(){
      if($('.aplayer-button').hasClass('aplayer-play')) {
        $('.aplayer-lrc').removeClass('lrc-show');
      } else {
        $('.aplayer-lrc').addClass('lrc-show');
      }
    })
  });
</script>
</html>
